import { useEffect, useMemo } from "react";
import { useEdges, useInternalNode, useNodes, useStore } from "@xyflow/react";
import { debounce, isEqual } from "lodash-es";

function shallowCompareNodes(arr1, arr2) {
    if (arr1 === arr2) return true;
    if (!arr1 || !arr2 || arr1.length !== arr2.length) return false;

    return arr1.every((node1, i) => {
        const node2 = arr2[i];
        return node1?.id === node2?.id &&
            node1?.type === node2?.type &&
            isEqual(node1?.data, node2?.data);
    });
}
function shallowCompareEdges(arr1, arr2) {
    if (arr1 === arr2) return true;
    if (!arr1 || !arr2 || arr1.length !== arr2.length) return false;

    return arr1.every((edge1, i) => {
        const edge2 = arr2[i];
        return edge1?.id === edge2?.id &&
            edge1?.type === edge2?.type &&
            edge1?.source === edge2?.source &&
            edge1?.target === edge2?.target
    });
}
const debounceNodes = s=> s.nodes // debounce(s=> s.nodes, 0)
const debounceEdges = s=> s.edges // debounce(s=> s.edges, 0)
export const usePreviousNodes = (currentId, filterTypes) => {
    const edges = useStore(debounceEdges, shallowCompareEdges)
    const nodes = useStore(debounceNodes, shallowCompareNodes)

    // console.error('进入usePreviousNodes')
    // useEffect(() => {
    //     console.error('edges11111')
    // }, [edges])
    // useEffect(() => {
    //     console.error('nodes')
    // }, [nodes])
    return useMemo(() => {
        // console.error('重新计算')
        const es = edges?.filter(e => {
            return e.target === currentId
        })
        return es?.reduce((acc, cur) => {
            const ns = nodes?.find(n => n.id === cur.source)
            ns && acc.push(ns)
            return acc
        }, [])?.filter(n => filterTypes?.length ? filterTypes.includes(n.type) : true) ?? []
    }, [currentId, filterTypes, nodes, edges])
}